package com.bianguo.android.functiondemo.task;

import android.os.AsyncTask;

import com.bianguo.android.functiondemo.adapter.ReptileAdapter;
import com.bianguo.android.functiondemo.utils.MLog;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReptileTask extends AsyncTask<String, Integer, ArrayList<String>> {

    public static final String WEB_URL = "http://search.dangdang.com/?key=%BB%FA%D0%B5%B1%ED&act=input";
    public static final String WEB_FILE_PATH = "H:\\java_file\\dangdang.txt";
    public static final String REGULE_IP_ADDRESS = "<a .*href=.+</a>";
    private static final String REGULE_IP_IMAGE = "<img.*src=(.*?)[^>]*?>";
    private static final String REGULE_IMGSRC_REG = "http:\"?(.*?)(\"|>|\\s+)";
    private ReptileAdapter adapter;

    public ReptileTask(ReptileAdapter adapter) {
        this.adapter = adapter;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected ArrayList<String> doInBackground(String... params) {
        ArrayList<String> results = new ArrayList<>();
        try {
            URL url = new URL(params[0]);
            URLConnection connection = url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(false);
            InputStream is = connection.getInputStream();
            connection.connect();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "GB2312"));
            String line = null;
//            File file = new File(WEB_FILE_PATH);
//            File dirFile = file.getParentFile();
//            if (!dirFile.exists()) {
//                dirFile.mkdirs();
//            }
//            if (file.exists()) {
//                file.delete();
//            }
//            PrintWriter pw = new PrintWriter(file, "GB2312");
            Pattern ipPattern = Pattern.compile(REGULE_IP_IMAGE);
//            ArrayList<String> urls = new ArrayList<>();
            int count = 0;
            while ((line = br.readLine()) != null) {
                Matcher m = ipPattern.matcher(line);
                while (m.find()) {
                    String href = m.group();
                    Matcher matcher = Pattern.compile(REGULE_IMGSRC_REG).matcher(href);
                    while (matcher.find()) {
                        String imageUrl = matcher.group();
                        imageUrl = imageUrl.trim();
                        imageUrl = imageUrl.substring(0, imageUrl.length() - 1);
                        if (imageUrl.endsWith("jpg") || imageUrl.endsWith("jpeg") || imageUrl.endsWith("png")
                                || imageUrl.endsWith("gif")) {
                            results.add(imageUrl);
                            count++;
                            publishProgress(count);
                        }
                    }
                }
            }
//            pw.close();
            br.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return results;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(ArrayList<String> results) {
        super.onPostExecute(results);
        adapter.addAll(results);
    }
}
